<template>
    <div class="enterpriseInfo">
        <div class="container">
            <el-tabs v-model="activeName" class="pl30">
                <el-tab-pane label="基本信息" name="basicInfo">
                    <el-form label-width="100px">
                        <el-form-item label="企业名称">
                            <el-input size="small" :value="enterpriseInfo.name" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="客户端名称">
                            <el-input size="small" v-model="systemPlatformName"></el-input>
                        </el-form-item>
                        <el-form-item label="企业logo">
                            <input type="file" @change="picChange($event)" accept="image/*" id="enterpriseLogo" style="display:none" />
                            <div onclick="document.getElementById('enterpriseLogo').click();"
                                 style="width: 100px;height:100px;cursor: pointer;">
                                <div v-if="!logoUrl" class="addImg"><span class="iconfont icon-tianjia"></span></div>
                                <el-image v-else style="width: 100px;height: 100px;" :src="logoUrl"></el-image>
                            </div>
                        </el-form-item>
                        <el-form-item label="并发量">1</el-form-item>
                        <el-form-item label="机器人数量">1</el-form-item>
                        <el-form-item label="是否多组织">是</el-form-item>
                        <el-form-item>
                            <el-button type="primary" size="small" @click="saveInfo">保存</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="安全机制" name="safety">
                    <el-form label-width="140px">
                        <el-form-item label="AppKey">
                            <el-input :value="enterpriseInfo.appKey" size="small" disabled></el-input>
                        </el-form-item>
                        <el-form-item label="AppSecret">
                            <el-input :value="enterpriseInfo.appSecret" size="small" disabled></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" size="small" @click="reset">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </div>

        <!-- 重置AppSecret -->
        <el-dialog :visible="resetVisible" title="重置AppSecret" width="640px" @close="resetCancel" class="resetSecret">
            <el-form ref="resetForm" :model="resetForm" :rules="resetRules">
                <el-form-item prop="graphCaptcha" class="flexItem">
                    <el-input v-model="resetForm.graphCaptcha" size="small" placeholder="请输入图形验证码"></el-input>
                    <img :src="graphCaptchaData.base64GraphCaptcha" @click="getGraphCaptcha" />
                </el-form-item>
                <el-form-item prop="smsCaptcha" class="flexItem">
                    <el-input v-model="resetForm.smsCaptcha" size="small" placeholder="请输入短信验证码"></el-input>
                    <el-button @click="sendSmsCaptcha" :disabled="isDisabled" type="primary" size="small" plain>{{buttonName}}</el-button>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" type="text" @click="resetCancel">取消</el-button>
                <el-button type="primary" size="small" @click="resetSubmit">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { updateEnterprise, sendSmsCaptcha, verifySmsCaptcha, resetAppSecret } from "@/api/systemConfig";
import { getGraphCaptcha, verifyGraphCaptcha } from "@/api/login";
import { lingYanUpload } from "@/utils/upload";
import { mapGetters } from "vuex";
export default {
    name: "enterpriseInfo",
    data() {
        var validateGraphCaptcha = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入图形验证码'));
            } else {
                if (this.isSend) {
                    callback();
                } else {
                    var param = {
                        graphCaptcha: this.resetForm.graphCaptcha,
                        graphCaptchaId: this.graphCaptchaData.id
                    }
                    verifyGraphCaptcha(param).then(resp => {
                        if (resp.status == 0) {
                            callback();
                        } else {
                            callback(new Error(resp.message));
                        }
                    });
                }
            }
        }
        var validateSmsCaptcha = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入短信验证码'));
            } else {
                if (!this.isSend) {
                    callback(new Error('请先点击发送短信验证码'));
                } else {
                    callback();
                }
            }
        }
        return {
            activeName: "basicInfo",
            systemPlatformName: "",
            logoUrl: "",
            resetVisible: false,
            graphCaptchaData: {},
            countDown: 60,//倒计时
            buttonName: "发送短信验证码",//按钮初始化文字
            isDisabled: false,//是否禁用按钮
            isSend: false,
            timeStamp: null, //重新发送时间戳
            resetForm: {
                graphCaptcha: "",
                smsCaptcha: ""
            },
            resetRules: {
                graphCaptcha: [{ required: true, validator: validateGraphCaptcha, trigger: 'blur' }],
                smsCaptcha: [{ required: true, validator: validateSmsCaptcha, trigger: 'blur' }],
            }
        }
    },
    mounted() {
        this.systemPlatformName = this.enterpriseInfo.systemPlatformName;
        this.logoUrl = this.enterpriseInfo.logoUrl;
    },
    methods: {
        saveInfo() {
            var param = {
                id: this.enterpriseInfo.id,
                systemPlatformName: this.systemPlatformName,
                logoUrl: this.logoUrl
            }
            updateEnterprise(param).then(resp => {
                if (resp.status == 0) {
                    this.$store.dispatch("user/setEnterpriseInfo", param);
                    this.$antMessage.success("修改成功");
                } else {
                    this.$antMessage.warning(resp.message);
                }
            });
        },
        async picChange(event) {
            var uuid = "uuid-" + new Date().getTime();
            var upload = await lingYanUpload(event.target.files[0], uuid);
            if (upload?.data?.remoteURL) {
                this.logoUrl = upload.data.remoteURL;
            }
        },
        reset() {
            this.getGraphCaptcha();
            this.resetVisible = true;
        },
        getGraphCaptcha() {
            getGraphCaptcha().then(resp => {
                if (resp.status == 0) {
                    this.graphCaptchaData = resp.data;
                }
            });
        },
        sendSmsCaptcha() {
            if (!this.isDisabled) {
                this.isDisabled = true;
                this.$refs['resetForm'].validateField("graphCaptcha", valid => {
                    if (!valid) {
                        this.isSend = true;
                        var param = {
                            graphCaptcha: this.resetForm.graphCaptcha,
                            graphCaptchaId: this.graphCaptchaData.id,
                        }
                        sendSmsCaptcha(param).then(resp => {
                            if (resp.status == 0) {
                                this.timeStamp = new Date().getTime() + resp.data.leftTimeToResend;
                                this.countDown = (resp.data.leftTimeToResend) / 1000;
                                this.countTime();
                            } else {
                                this.isDisabled = this.isSend = false;
                                this.$antMessage.warning(resp.message);
                            }
                        });
                    } else {
                        this.isDisabled = false;
                    }
                });
            }
        },
        countTime() {
            let timerId = setInterval(() => {
                this.countDown--;
                this.buttonName = this.countDown + "秒后重试";
                if (this.countDown <= 0) {
                    clearInterval(timerId);
                    this.timeStamp = null;
                    this.buttonName = "发送短信验证码";
                    this.countDown = 60;
                    this.isDisabled = this.isSend = false;
                }
            }, 1000);
        },
        resetCancel() {
            this.resetVisible = false;
            this.$refs['resetForm'].resetFields();
        },
        resetSubmit() {
            this.$refs['resetForm'].validate((valid) => {
                if (valid) {
                    this.$confirm("请确定是否重置？重置会导致原有的AppSecret时效！", "提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    }).then(() => {
                        var param = {
                            smsCaptcha: this.resetForm.smsCaptcha
                        }
                        verifySmsCaptcha(param).then(resp => {
                            if (resp.status == 0) {
                                resetAppSecret(param).then(response => {
                                    if (response.status == 0) {
                                        this.resetCancel();
                                        this.$store.dispatch("user/setEnterpriseInfo", { appSecret: response.data });
                                        this.$antMessage.success("操作成功");
                                    } else {
                                        this.$antMessage.warning(response.message);
                                    }
                                });
                            } else {
                                this.$antMessage.warning(resp.message);
                            }
                        });
                    }).catch(() => { });
                }
            });
        }
    },
    created() {
        window.addEventListener('beforeunload', () => {
            if (this.timeStamp) {
                localStorage.setItem("resetSecretTime", this.timeStamp);
            }
        })
        this.timeStamp = localStorage.getItem("resetSecretTime") || null;
        if (this.timeStamp) { //刷新页面、跳转路由倒计时继续
            let nowStamp = new Date().getTime();
            var stamp = this.timeStamp - nowStamp;
            if (stamp <= 0) {
                this.buttonName = "发送短信验证码";
                this.isDisabled = false;
            } else {
                this.isDisabled = true;
                this.countDown = parseInt(Math.abs(stamp) / 1000);
                this.countTime();
            }
            localStorage.removeItem("resetSecretTime");
        }
    },
    beforeRouteLeave(to, from, next) {
        if (this.timeStamp) {
            localStorage.setItem("resetSecretTime", this.timeStamp);
        }
        next();
    },
    computed: {
        ...mapGetters(["enterpriseInfo"]),
    },
}
</script>

<style lang="scss">
.enterpriseInfo {
    .el-tabs__header {
        margin-bottom: 60px;
    }
    .container {
        .el-form-item__content {
            width: 680px;
        }
        .addImg {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100px;
            height: 100px;
            background: #f5f7fa;
            border: 1px solid #dae1e9;
            border-radius: 6px;
            .iconfont {
                font-size: 26px;
                color: #b7c1c9;
            }
        }
    }
    .resetSecret {
        .el-dialog__body {
            padding-top: 30px;
        }
        .flexItem .el-form-item__content {
            display: flex;
            align-items: center;
            .el-input__inner {
                border-radius: 6px;
            }
            .el-button,
            img {
                cursor: pointer;
                width: 160px;
                height: 34px;
                flex-shrink: 0;
                margin-left: 20px;
            }
            img {
                border-radius: 6px;
                border: 1px solid #6b5ee2;
            }
        }
    }
}
</style>